#include "../Include/link_pub.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <mysql/mysql.h>

static MYSQL* conn = NULL;

// 数据库连接函数
int init_database() {
    conn = mysql_init(NULL);
    if (conn == NULL) {
        fprintf(stderr, "MySQL init failed\n");
        return -1;
    }
    
    // 从配置文件读取数据库连接信息
    FILE* conf = fopen("database.conf", "r");
    if (conf == NULL) {
        fprintf(stderr, "Cannot open database config file\n");
        return -1;
    }
    
    char host[100], user[100], pass[100], db[100];
    fscanf(conf, "%s %s %s %s", host, user, pass, db);
    fclose(conf);
    
    if (mysql_real_connect(conn, host, user, pass, db, 0, NULL, 0) == NULL) {
        fprintf(stderr, "MySQL connection failed: %s\n", mysql_error(conn));
        mysql_close(conn);
        return -1;
    }
    
    return 0;
}

void close_database() {
    if (conn != NULL) {
        mysql_close(conn);
    }
}

// 从数据库加载学生数据
Student* load_students_from_db() {
    Student* head = NULL;
    char query[] = "SELECT * FROM students";
    
    if (mysql_query(conn, query)) {
        fprintf(stderr, "Query failed: %s\n", mysql_error(conn));
        return NULL;
    }
    
    MYSQL_RES* result = mysql_store_result(conn);
    if (result == NULL) {
        return NULL;
    }
    
    MYSQL_ROW row;
    while ((row = mysql_fetch_row(result))) {
        Student* student = (Student*)malloc(sizeof(Student));
        if (!student) {
            mysql_free_result(result);
            return head;
        }
        
        strcpy(student->student_id, row[0]);
        strcpy(student->name, row[1]);
        student->total_credits = atoi(row[2]);
        student->course_count = 0; // 从enrollments表获取
        memset(student->selected_courses, 0, sizeof(student->selected_courses));
        student->next = NULL;
        
        // 获取该学生选课信息
        char course_query[256];
        sprintf(course_query, "SELECT c.course_id FROM courses c JOIN enrollments e ON c.course_id = e.course_id WHERE e.student_id = '%s'", student->student_id);
        
        if (mysql_query(conn, course_query) == 0) {
            MYSQL_RES* course_result = mysql_store_result(conn);
            MYSQL_ROW course_row;
            int i = 0;
            while ((course_row = mysql_fetch_row(course_result)) && i < 100) {
                strcpy(student->selected_courses[i], course_row[0]);
                i++;
            }
            student->course_count = i;
            mysql_free_result(course_result);
        }
        
        head = add_student(head, student);
    }
    
    mysql_free_result(result);
    return head;
}

// 从数据库加载课程数据
Course* load_courses_from_db() {
    Course* head = NULL;
    char query[] = "SELECT * FROM courses";
    
    if (mysql_query(conn, query)) {
        fprintf(stderr, "Query failed: %s\n", mysql_error(conn));
        return NULL;
    }
    
    MYSQL_RES* result = mysql_store_result(conn);
    if (result == NULL) {
        return NULL;
    }
    
    MYSQL_ROW row;
    while ((row = mysql_fetch_row(result))) {
        Course* course = (Course*)malloc(sizeof(Course));
        if (!course) {
            mysql_free_result(result);
            return head;
        }
        
        strcpy(course->course_id, row[0]);
        strcpy(course->course_name, row[1]);
        strcpy(course->course_type, row[2]);
        course->teaching_hours = atoi(row[3]);
        course->credits = atoi(row[4]);
        course->max_capacity = atoi(row[5]);
        course->enrolled_count = atoi(row[6]);
        
        // 初始化学生列表
        memset(course->enrolled_students, 0, sizeof(course->enrolled_students));
        course->next = NULL;
        
        // 获取选课学生信息
        char student_query[256];
        sprintf(student_query, "SELECT s.student_id FROM students s JOIN enrollments e ON s.student_id = e.student_id WHERE e.course_id = '%s'", course->course_id);
        
        if (mysql_query(conn, student_query) == 0) {
            MYSQL_RES* student_result = mysql_store_result(conn);
            MYSQL_ROW student_row;
            int i = 0;
            while ((student_row = mysql_fetch_row(student_result)) && i < 1000) {
                strcpy(course->enrolled_students[i], student_row[0]);
                i++;
            }
            course->enrolled_count = i;
            mysql_free_result(student_result);
        }
        
        head = add_course(head, course);
    }
    
    mysql_free_result(result);
    return head;
}

// 保存学生数据到数据库
int save_students_to_db(Student* head) {
    mysql_query(conn, "DELETE FROM enrollments");
    mysql_query(conn, "DELETE FROM students WHERE student_id != '0'");
    
    Student* current = head;
    while (current != NULL) {
        char query[512];
        sprintf(query, "INSERT INTO students (student_id, student_name, total_credits) VALUES ('%s', '%s', %d) ON DUPLICATE KEY UPDATE student_name='%s', total_credits=%d",
                current->student_id, current->name, current->total_credits, current->name, current->total_credits);
        
        if (mysql_query(conn, query)) {
            fprintf(stderr, "Insert failed: %s\n", mysql_error(conn));
            return -1;
        }
        
        current = current->next;
    }
    
    return 0;
}

// 保存课程数据到数据库
int save_courses_to_db(Course* head) {
    if (conn == NULL) {
        fprintf(stderr, "Database not connected\n");
        return -1;
    }

    if (mysql_query(conn, "DELETE FROM enrollments WHERE 1=1")) {
        fprintf(stderr, "Failed to clear enrollments: %s\n", mysql_error(conn));
    }
    
    if (mysql_query(conn, "DELETE FROM courses WHERE 1=1")) {
        fprintf(stderr, "Failed to clear courses: %s\n", mysql_error(conn));
        return -1;
    }

    Course* current = head;
    int inserted_count = 0;
    while (current != NULL) {
        char query[512];
        snprintf(query, sizeof(query), "INSERT INTO courses (course_id, course_name, course_type, course_hours, credits, max_enrollment, current_enrollment) VALUES ('%s', '%s', '%s', %d, %d, %d, %d)",
                current->course_id, current->course_name, current->course_type, 
                current->teaching_hours, current->credits, current->max_capacity, current->enrolled_count);
        
        if (mysql_query(conn, query)) {
            fprintf(stderr, "Insert failed: %s\n", mysql_error(conn));
            return -1;
        }
        inserted_count++;
        current = current->next;
    }
    
    printf("DEBUG: Saved %d courses to database\n", inserted_count);
    return 0;
}

// 保存选课关系到数据库
int save_enrollments_to_db(Student* student_head) {
    mysql_query(conn, "DELETE FROM enrollments");
    
    Student* student = student_head;
    while (student != NULL) {
        for (int i = 0; i < student->course_count; i++) {
            char query[256];
            sprintf(query, "INSERT INTO enrollments (student_id, course_id) VALUES ('%s', '%s')",
                    student->student_id, student->selected_courses[i]);
            mysql_query(conn, query);
        }
        student = student->next;
    }
    
    return 0;
}

void log_operation(const char* operation, const char* details) {
    FILE* log = fopen("log.log", "a");
    if (log) {
        time_t now;
        time(&now);
        char time_str[100];
        ctime_r(&now, time_str);
        time_str[strcspn(time_str, "\n")] = 0;
        fprintf(log, "[%s] %s: %s\n", time_str, operation, details);
        fclose(log);
    }
}